<template>
  <transition :name="dir">
    <div v-show="selfIndex===currentIndex" class="yd-carItem">
      <slot></slot>
    </div>
  </transition>
</template>

<script>
import { getCurrentInstance, reactive, toRefs, watch } from "vue";
export default {
  name: "CarItem",
  setup() {
    const instance = getCurrentInstance(); // this.$
    const state = reactive({
      selfIndex: instance.parent.slots.default()[0].children.findIndex(v => {
        return v.key === instance.vnode.key;
      }),
      currentIndex: instance.parent.ctx.currentIndex,
      dir: instance.parent.ctx.dir
    });
    watch(
      () => instance.parent.ctx.currentIndex,
      value => {
        state.currentIndex = value;
      }
    );
    watch(
      () => instance.parent.ctx.dir,
      value => {
        state.dir = value;
      }
    );
    return {
      ...toRefs(state)
    };
  }
};
</script>


<style lang="scss" scoped>
.yd-carItem {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  img {
    width: 100%;
    height: 100%;
  }
}
// .v-enter .v-leave动画类不生效
// next
.next-enter-active {
  transform: translateX(100%);
}
.next-enter-to {
  transform: translateX(0);
}
.next-leave-active {
  transform: translateX(0);
}
.next-leave-to {
  transform: translateX(-100%);
}
.next-enter-active,
.next-leave-active {
  transition: all 0.5s linear;
}
// prev
.prev-enter-active {
  transform: translateX(-100%);
}
.prev-enter-to {
  transform: translateX(0);
}
.prev-leave-active {
  transform: translateX(0);
}
.prev-leave-to {
  transform: translateX(100%);
}
.prev-enter-active,
.prev-leave-active {
  transition: all 0.5s linear;
}
</style>